//
//  YGUserAccuntViewModel.swift
//  sinaWeiBoGui
//
//  Created by liyonggui on 16/5/13.
//  Copyright © 2016年 liyonggui. All rights reserved.
//

import UIKit

class YGUserAccountViewModel: NSObject {
    
    // 单例
    static let sharedInstance: YGUserAccountViewModel = YGUserAccountViewModel()
    
    // 获取沙盒路径
    let userAccluntPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/account.plist"
    
    /// 全局唯一的账号
    var userAccount: YGUserAccount?
    
    /// 用户是否登录
    var isUserLogin: Bool {
        get {
            return userAccount != nil
        }
    }
    
    override init() {
        super.init()
        
        userAccount = loadUserAccount()
    }
    
    /// 请求获取AccessToken
    func loadAccessToken(code: String, callBack: (error: NSError?) -> ()) {
        
        // 发送POST请求获取AccessToken
        let urlString = "oauth2/access_token"
        
        // 参数
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri": redirect_uri
        ]
        
        YGNetworkTool.sharedInstance.request(requesMethod.POST, URLString: urlString, parameters: parameters, success: { (task, responseObject) -> Void in
            
//            YGPrint(items: "获取AccessToken成功: \(responseObject)")
            
            // 判断返回的数据是否能转换为字典
            if let result = responseObject as? [String: AnyObject] {
                
                // 字典转模型
                let userAccount = YGUserAccount(dic: result)
//                YGPrint(items: "\(userAccount)")
                
//                YGPrint(items: "\(userAccluntPath)")
                // 将账号赋值给属性
                self.userAccount = userAccount
                
                // 调用归档方法,保存到沙盒
//                NSKeyedArchiver.archiveRootObject(useAccount, toFile: self.userAccluntPath)
                self.saveUserAccount()
                
                // 告诉控制器保存完毕
                callBack(error: nil)
                
            } else {
                YGPrint(items: "返回数据转字典失败了")
            }
            
            }, failure: { (task, error) -> Void in
//                YGPrint(items: "失败了：\(error)")
                callBack(error: error)
        })
    }
    
    /// 保存到沙盒
    private func saveUserAccount() {
        if let account = userAccount {
        NSKeyedArchiver.archiveRootObject(account, toFile: self.userAccluntPath)
        }
    }
    
    /// 解档账号
    func loadUserAccount() -> YGUserAccount? {
        
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(userAccluntPath) as? YGUserAccount {
            if account.expiresDate?.compare(NSDate()) != NSComparisonResult.OrderedAscending {
                // 没有过期
                return account
            } else {
                // 过期了
                return nil
            }
        }
        // 没有加载出账号
        return nil
    }
    
    // MARK: - 加载用户信息
    func losdUserInfo(loadUserInfoCallBack:() -> ()) {
        
        // https://api.weibo.com/2/users/show.json?access_token=2.006LuhaCrY1jcD8f1e5b55c3UPomuB&uid=2374677835
        // ttps://api.weibo.com/2/users/show.json?access_token=2.006LuhaCrY1jcD8f1e5b55c3UPomuB&uid=2374677835
        
        // access_token 是否有值
        guard let access_token = userAccount?.access_token else {
            YGPrint(items: "access_token没有值")
            return
        }
        
        // uid 是否有值
        guard let uid = userAccount?.uid else {
            YGPrint(items: "uid没有值")
            return
        }
        
        let urlString = "2/users/show.json?"
        // 参数
        let parameters = [
            "access_token" : access_token,
            "uid" : uid
        ]
        
        /// 发送请求
        YGNetworkTool.sharedInstance.request(requesMethod.GET, URLString: urlString, parameters: parameters, success: { (_, responseObject) -> Void in
//            YGPrint(items: "\(responseObject)")
            if let result = responseObject as? [String: AnyObject] {
                // 用户头像与用户名称
                let screen_name = result["screen_name"] as? String
                let avatar_large = result["avatar_large"] as? String
                
                // 赋值到当前账号
                self.userAccount?.screen_name = screen_name
                self.userAccount?.avatar_large = avatar_large
                
                // 保存到沙盒
                self.saveUserAccount()
                
                // 回调闭包，显示信息
                loadUserInfoCallBack()
            }
            
            }) { (_, error) -> Void in
                YGPrint(items: "获取用户信息失败：\(error)")
        }
        
    }
    

}














